package com.enjoy.dubbospi;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.rpc.Protocol;
import org.junit.Test;

import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>TODO</p>
 *
 * @Author Ellison Pei
 * @Date 2021/8/16 16:56
 **/
public class SpiTest {
    // 用逗号分隔
    private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*");

    @Test
    public void adaptive() {
        //@Adaptive 有单独的api那实现了这个注解的实现类
        ActivateApi adaptiveExtension = ExtensionLoader.getExtensionLoader(ActivateApi.class).getAdaptiveExtension();
        System.out.println(adaptiveExtension.getClass());
    }

    /**
     * getActivateExtension
     * 1、首先看分组，如果值@Activate只配置了分组，那么就只匹配分组值
     * 2、会匹配url中的参数，如果分组和value都配置了。首先匹配分组，然后在匹配url中的参数key
     */
    @Test
    public void test1() {
        URL url = URL.valueOf("test://localhost/test");
        url = url.addParameter("value1", "gggg");
        //只看分组，不看url中的参数
        List<ActivateApi> rabbitmq = ExtensionLoader.getExtensionLoader(ActivateApi.class).getActivateExtension(url, new String[]{"spring"}, "rabbitmq");
        System.out.println(rabbitmq.size());
        for (ActivateApi activateApi : rabbitmq) {
            System.out.println(activateApi.getClass());
        }
    }

    @Test
    public void defaultL() {
        //寻找@SPI注解中配置的value值
        System.out.println(ExtensionLoader.getExtensionLoader(ActivateApi.class).getDefaultExtension());
        System.out.println(ExtensionLoader.getExtensionLoader(ActivateApi.class).getDefaultExtensionName());

        //根据指定的name拿值
        System.out.println(ExtensionLoader.getExtensionLoader(ActivateApi.class).getExtension("mybatis"));
        System.out.println(ExtensionLoader.getExtensionLoader(ActivateApi.class).getSupportedExtensions());
    }
    @Test
    public void protocol() {
        Protocol adaptiveExtension = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
        System.err.println(adaptiveExtension);
    }

    @Test
    public void testRegular(){
        String str = "1900-01-01 2007/08/13 1900.01.01 ,1900 01 01 1900-01.01 ,1900 13 01 1900 02 31";
        String[] split = NAME_SEPARATOR.split(str);
        for (int i = 0; i < split.length; i++) {
            System.out.println(i + ": " + split[i]);
        }
    }
}
